
import {
  loginApi,
  userInfoApi,
  getMessageDetailApi,
  getMessageListByUserIdApi,
  getMessageNumByUserIdApi,
  modifyByReadApi,
  systemStatusApi,
  removeMessageApi,
  logoutApi,
  listRoleResourceApi,
  uploadBell
} from '@/services/user.js';
import { setAuthorization, removeAuthorization } from '@/utils/request';
import { encryptedData } from '@/utils/util';
import { message } from 'ant-design-vue';
import { presOpen } from '@/utils/pres';
export default {
  namespaced: true,
  state: {
    logging: false,
    // 消息
    noticeList: [],
    noticeList0: [],
    noticeLoading: false,
    noticeNum: 0,
    readLoading: false,
    userInfo: '',
    systemStatus: [],
    systemStatusLoading: false,
    listRoleResourceApi: []
  },
  getters: {
    userInfo(state) {
      return state.userInfo || JSON.parse(localStorage.getItem(process.env.VUE_APP_USERINFO));
    },
    menuList(state) {
      return (state.userInfo?.menus || JSON.parse(localStorage.getItem(process.env.VUE_APP_USERINFO))?.menus || []);
    },
    listRoleResource(state) {
      return (state.listRoleResource || JSON.parse(localStorage.getItem('listRoleResource')) || []);
    }
  },
  mutations: {
    setState(state, { key, payload }) {
      state[key] = payload;
    }
  },
  actions: {
    // 上传提示音
    ac_uploadBell({ commit }, payload) {
      return new Promise((resolve, reject) => {
        uploadBell(payload).then(res => {
          if (res.code == 200) {
            resolve(true)
          } else {
            reject(fasle)
          }
        }).catch(e => {
          reject(fasle)
        })
      })
    },
    // 登入
    async login({ commit, dispatch }, payload) {
      commit('setState', { key: 'logging', payload: true });
      try {
        const { username, password } = payload;
        const pk = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCBRe2A2rMu0vb3QBZdn8qMTnPDOdW3Q9aYOEIVRSlYXMHUU+0ruaK+FR1YB/juFr9ReHnqtOxzv8ECUexL2dppgLPAP1OvX7B/YSyhORD+3VfsKlBCXLSM5+bEF9KAR8BJK72SU3A5R9z61Zae43+A/B9saxt3cu/94WrXE2YvcwIDAQAB';
        const params = {
          username,
          password: encryptedData(pk, password)
        };
        //
        const loginRep = await loginApi(params);
        if (loginRep.code === 200) {
          const tokenExpire = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000);
          setAuthorization({ token: loginRep.data.token, expireAt: tokenExpire });
          dispatch('afterLogin');
          // const infoRep = await userInfoApi();
          // localStorage.setItem(process.env.VUE_APP_USERINFO, JSON.stringify(infoRep.data));
          // commit('setState', { key: 'userInfo', payload: infoRep.data });
          // const userName = getters?.userInfo?.username ? `，${getters?.userInfo?.username}` : '';
          // message.success(`欢迎回来${userName}`);

          // // 权限跳转首页
          // const menuList = getters.menuList;
          // if (!presOpen) {
          //   window.cusRouter.push('/fraMonitoring');
          // } else {
          //   const a = ['机队状态', '事件监控', '资源工具'];
          //   if (menuList.findIndex(item => item.title === a[0]) > -1) {
          //     window.cusRouter.push('/fraMonitoring');
          //   } else if (menuList.findIndex(item => item.title === a[1]) > -1) {
          //     window.cusRouter.push('/eventMonitoring');
          //   } else if (menuList.findIndex(item => item.title === a[2]) > -1) {
          //     window.cusRouter.push('/resourceTool');
          //   } else {
          //     window.cusRouter.push('/403');
          //   }
          // }
        } else {
          message.error(loginRep.message);
        }
      } finally {
        commit('setState', { key: 'logging', payload: false });
      }
    },
    afterLogin({ commit, dispatch }, payload) {
      dispatch('userInfo');
      dispatch('listRoleResource');
    },
    async userInfo({ commit, getters, dispatch }) {
      const infoRep = await userInfoApi();
      if (infoRep.code === 200) {
        if (process.env.VUE_APP_CURENV === 'sso-production' || process.env.VUE_APP_CURENV === 'sso-development') {
          const tokenExpire = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000);
          setAuthorization({ token: '123123', expireAt: tokenExpire });
        }

        infoRep.data.menus.forEach(element => {
          if (element.parentId === '0' && element.title === '故障历史') {
            element.title = '故障历史0';
          }
        });

        localStorage.setItem(process.env.VUE_APP_USERINFO, JSON.stringify(infoRep.data));
        commit('setState', { key: 'userInfo', payload: infoRep.data });

        // option 中的用户自定义设置的本地缓存  如果和上一次登陆userid不同则重置
        const cUsid = localStorage.getItem('usid') ?? '';
        if (cUsid !== infoRep.data.userId) {
          dispatch('resetUserOption');
        }

        localStorage.setItem('usid', infoRep.data.userId);

        // 关于我们
        dispatch('setting/showVersion', { checkRead: true }, { root: true });

        const userName = getters?.userInfo?.username ? `，${getters?.userInfo?.username}` : '';
        message.success(`欢迎回来${userName}`);

        // 权限跳转首页
        const menuList = getters.menuList;
        if (localStorage.getItem('from') &&
          localStorage.getItem('from') !== '/login' &&
          localStorage.getItem('from') !== '403' &&
          localStorage.getItem('from') !== '404' && localStorage.getItem('from') !== '/reportsLayout') {
          window.cusRouter.push(localStorage.getItem('from'));
          localStorage.removeItem('from');
        } else {
          if (!presOpen) {
            window.cusRouter.push('/fraMonitoring');
          } else {
            const a = ['机队状态', '事件监控', '资源工具'];
            if (menuList.findIndex(item => item.title === a[0]) > -1) {
              window.cusRouter.push('/fraMonitoring');
            } else if (menuList.findIndex(item => item.title === a[1]) > -1) {
              window.cusRouter.push('/eventMonitoring');
            } else if (menuList.findIndex(item => item.title === a[2]) > -1) {
              window.cusRouter.push('/resourceTool');
            } else {
              window.cusRouter.push('/403');
            }
          }
        }
      } else if (infoRep.code === 1000) {
        if (process.env.VUE_APP_CURENV === 'sso-production') {
          // location.href = `${infoRep.data.uri}?currentPath=${location.href}`;
          location.href = `${infoRep.data.uri}`;
        } else if (process.env.VUE_APP_CURENV === 'sso-development') {
          console.log(`${infoRep.data.uri}?currentPath=${location.href}`);
        }
      } else if (infoRep.code !== 200 && infoRep.code !== 1000) {
        window.cusRouter.push('/403');
      }
    },
    async listRoleResource() {
      const rrRep = await listRoleResourceApi();
      const newData = (rrRep.data ?? []).flatMap(item => item.resourceCode);
      localStorage.setItem('listRoleResource', JSON.stringify(newData));
    },
    // 重置自定义设置
    resetUserOption({ dispatch }) {
      localStorage.removeItem('hspr');
      localStorage.removeItem('openType');
      localStorage.removeItem('fleetStatusClickEvent');
      localStorage.removeItem('fmTableS');
      localStorage.removeItem('emSF');
      localStorage.removeItem('fmSF');
      dispatch('setting/showVersion', {}, { root: true });
    },
    // 登出
    async logOut() {
      localStorage.removeItem('userInfo');
      localStorage.removeItem('eRow');
      localStorage.removeItem('showModal');
      localStorage.removeItem('apInfoCode');
      localStorage.removeItem('row');
      localStorage.removeItem('scRow');
      localStorage.removeItem('from');
      localStorage.removeItem('listRoleResource');
      removeAuthorization();
      // window.cusRouter.push('/login');
      if (process.env.VUE_APP_CURENV === 'sso-production') {
        try {
          const outRep = await logoutApi();
          if (outRep.code === 200) {
            // location.href = `${infoRep.data.uri}?currentPath=${location.href}`;
            location.href = `${outRep.data.uri}&backUrl=${location.href}`;
          } else if (process.env.VUE_APP_CURENV === 'sso-development') {
            console.log(`${outRep.data.uri}?currentPath=${location.href}`);
          }
        } finally {
          // location.reload();
        }
        // location.href = `http://10.121.31.79/opcnet-sso/logout?service=${location.href}`;
      } else {
        window.cusRouter.push('/login');
      }
    },
    // 用户消息列表
    async getMessageListByUserId({ commit }, payload) {
      if (!payload.noLoading) {
        commit('setState', { key: 'noticeLoading', payload: true });
      }

      const rep = await getMessageListByUserIdApi(payload);
      commit('setState', { key: 'noticeList', payload: rep.data });
      commit('setState', { key: 'noticeList0', payload: rep.data?.filter(v => v.read == 0) });
      commit('setState', { key: 'noticeLoading', payload: false });
    },
    // 消息详情
    getMessageDetail() {
      getMessageDetailApi();
    },
    // 用户消息条数
    async getMessageNumByUserId({ commit }, payload) {
      const rep = await getMessageNumByUserIdApi(payload);
      commit('setState', { key: 'noticeNum', payload: rep.data ?? 0 });
    },
    async getSystemStatus({ commit }) {
      commit('setState', { key: 'systemStatusLoading', payload: true });
      const rep = await systemStatusApi();
      commit('setState', { key: 'systemStatus', payload: rep.data });
      commit('setState', { key: 'systemStatusLoading', payload: false });
    },

    // 消息设置已读
    async modifyByRead({ state, commit }, payload) {
      // commit('setState', { key: 'readLoading', payload: true });

      try {
        const rep = await modifyByReadApi(payload);
        if (rep.code === 200) {
          if (payload.isAll) {
            commit('setState', { key: 'noticeNum', payload: 0 });
            message.success(rep.message);
          } else {
            commit('setState', { key: 'noticeNum', payload: Math.max(0, state.noticeNum - 1) });
          }

          return Promise.resolve(true);
        } else {
          // message.error(rep.message);
        }
      } finally {
        // commit('setState', { key: 'readLoading', payload: false });
      }
    },

    // 清除消息
    async removeMessage({ commit }, payload) {
      commit('setState', { key: 'readLoading', payload: true });

      try {
        const rep = await removeMessageApi(payload);
        if (rep.code === 200) {
          message.success(rep.message);
          commit('setState', { key: 'noticeNum', payload: 0 });
          return Promise.resolve(true);
        } else {
          message.error(rep.message);
        }
      } finally {
        commit('setState', { key: 'readLoading', payload: false });
      }
    }
  }
};
